package edu.sctu.zcy.month201506.day20150628test;

import javax.print.DocFlavor;
import java.io.*;

/**
 * Created by user24 on 2015/6/28.
 */
public class FileUtil {

    private String path;
    private String subPathOne;
    private String subPathTwo;
    public static String json = "";

    public FileUtil(String path,String subPathOne,String subPathTwo){

        this.path = path;
        this.subPathOne = subPathOne;
        this.subPathTwo = subPathTwo;

    }

    public File getJsonTxt(){
        return creatNewFile(path,subPathOne);
    }

    public File getAppBean(){
        return creatNewFile(path,subPathTwo);
    }

    public void saveJsonDataToJsonTxt(){

        try {
            FileWriter fileWriter = new FileWriter(getJsonTxt());
            fileWriter.write(HttpPostUtil.message);
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getDataOfJsonTxt() {

        byte[] bytes = new byte[1024];
        int count;

        try {
            FileInputStream fileInputStream = new FileInputStream(getJsonTxt());
            try {
                while ((count = fileInputStream.read(bytes)) != -1){

                    json = json+new String(bytes,0,count,"utf-8");
                }
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return json;
    }

    public void saveJsonDataToAppBean(){

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(getAppBean());
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);

            objectOutputStream.writeObject(JsonUtil.fastJson(getDataOfJsonTxt()));

            objectOutputStream.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public File creatFile(File file) {

        if(!file.exists()){
            file.mkdir();
        }
        return file;
    }

    public File creatNewFile(String dir,String fileName)  {

        File file1 = new File(dir+fileName);
        if(!file1.exists()){

            try {
                file1.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file1;
    }

}
